package com.ui.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ui.service.Impl.ProductServiceImpl;
import com.ui.service.Impl.ProductpicServiceImpl;
import com.ui.service.ProductService;
import com.wanmei.pojo.Product;
import com.wanmei.pojo.Productpic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

@Controller
public class WebUiProductListController {
    @Autowired
    private ProductServiceImpl service;
    @Autowired
    private ProductpicServiceImpl productpicService;
    /**
     * 商品列表
     * @return
     */
//    @RequestMapping("productlistView")
//    public String productListView() {
//        return "/productlist";
//    }

    @RequestMapping(value="productListView")
    @ResponseBody
    public ModelAndView productList(@RequestParam(value="currentPage",defaultValue="1")Integer pageNum,
                                    @RequestParam(value="pageSize",defaultValue = "10")Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Product> list = service.getProductList();
        PageInfo pageInfo = new PageInfo(list);
        ModelAndView model = new ModelAndView();
        model.addObject("pageInfo",pageInfo);
        model.setViewName("productlist");
        return model;
    }

    /**
     * public
     * 专门用来显示图片的接口
     */
    @RequestMapping("/showPic")
    public ResponseEntity<byte[]> showPicToJspss(@RequestParam("pid") int pid, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Productpic productpic = productpicService.selectOnePicUrl(pid);
        if (productpic != null && !productpic.getPicurl().isEmpty()) {
            File file = new File(productpic.getPicurl());
            System.out.println("");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<byte[]>(Files.readAllBytes(file.toPath()), headers, HttpStatus.CREATED);
        }
        return null;
    }
}
